//
//  VideoAssetPickerPreviewCell.swift
//  RNAsmanMaster
//
//  Created by 李旭峰 on 10/14/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

import UIKit
import FCUUID
import AVFoundation
import SnapKit

class VideoAssetPickerPreviewCell: UICollectionViewCell {
    weak var controller:XFImagePickerPreviewController?
    var model:MTImagePickerModel!
    var avPlayer:AVPlayer!
    private var playerLayer:AVPlayerLayer!
    private var observer:AnyObject?

//    @IBOutlet weak var tempContentView: UIView!
//    @IBOutlet weak var avPlayerView: UIView!
//    @IBOutlet weak var imageView: UIImageView!
//    @IBOutlet weak var btnPlay: UIButton!
    
    private lazy var tempContentView: UIView = UIView()
    private lazy var avPlayerView: UIView = UIView()
    private lazy var imageView: UIImageView = UIImageView()
    private lazy var btnPlay: UIButton = UIButton(type: .custom)
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }

    required init?(coder: NSCoder) {
        super.init(frame: CGRect.zero)
        initView()
    }
    private func initView(){
        self.contentView.addSubview(self.tempContentView)
        self.tempContentView.snp.makeConstraints { (make) in
            make.leading.top.trailing.bottom.equalToSuperview()
        }
        self.tempContentView.addSubview(self.avPlayerView)
        self.avPlayerView.snp.makeConstraints { (make) in
            make.leading.top.trailing.bottom.equalToSuperview()
        }
        self.tempContentView.addSubview(self.imageView)
        self.imageView.snp.makeConstraints { (make) in
            make.leading.top.trailing.bottom.equalToSuperview()
        }
        self.btnPlay.addTarget(self, action: #selector(btnPlayTouch(_:)), for: .touchUpInside)
        self.tempContentView.addSubview(self.btnPlay)
        self.btnPlay.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }

        self.avPlayer = AVPlayer()
        self.playerLayer = AVPlayerLayer()
        self.playerLayer.player = self.avPlayer
        self.playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
        self.playerLayer.frame = UIScreen.main.compatibleBounds
        self.avPlayerView.layer.insertSublayer(self.playerLayer, at: 0)
        self.avPlayerView.isUserInteractionEnabled = false

        let singTapGesture = UITapGestureRecognizer(target: self, action: #selector(VideoAssetPickerPreviewCell.onVideoSingleTap(_:)))
        singTapGesture.numberOfTapsRequired = 1
        singTapGesture.numberOfTouchesRequired = 1
        self.addGestureRecognizer(singTapGesture)
    }
    override func prepareForReuse() {
      self.imageView.isHidden = false
      self.avPlayerView.isHidden = true
      self.btnPlay.isHidden = false
    }

    func initWithModel(model:MTImagePickerModel,controller:XFImagePickerPreviewController) {
      self.controller = controller
      self.model = model
      self.imageView.image = model.getPreviewImage()
    }

    //解决滚动卡顿，在滚动结束时替换AVPlayerItem
    func didScroll() {
      if let observer = self.observer {
          self.avPlayer.pause()
          self.avPlayer.removeTimeObserver(observer)
          self.observer = nil
          self.btnPlay.isHidden = false
          self.imageView.isHidden = false
          self.setTopAndBottomView(hidden: false)
      }
      self.setTopAndBottomView(hidden: false)
    }

    func resetLayer() {
      self.playerLayer.frame = UIScreen.main.compatibleBounds
    }

    func didEndScroll() {
      self.setTopAndBottomView(hidden: false)
      self.model.getImageAsync(){[weak self] image in
          guard let `self` = self else { return }
          self.imageView.image = image
      }
      //此处耗时,故放在滚动结束后调用
      let uuid = FCUUID.uuid()!
      self.model.getAVPlayerItemAsync(requestId: uuid) {[weak self] (playerItem, tempRequestId) in
          guard let `self` = self else { return }
          guard uuid == tempRequestId else {
              return
          }
          self.avPlayer.replaceCurrentItem(with: playerItem)
          if let currentItem = self.avPlayer.currentItem {
              self.avPlayer.addBoundaryTimeObserver(forTimes: [currentItem.asset.duration as NSValue], queue: nil) {
                  [weak self] in
                  DispatchQueue.main.async {
                    guard let `self` = self else { return }
                      self.avPlayer.seek(to: CMTime(value: 0 , timescale: 30))
                      self.btnPlay.isHidden = false
                      self.setTopAndBottomView(hidden: false)
                  }
                }
            }
      }
    }

    func resetLayer(frame:CGRect) {
      self.playerLayer.frame = frame
    }

    @objc func onVideoSingleTap(_ sernder:UITapGestureRecognizer) {
      self.playerPlayOrPause()
    }

    @IBAction func btnPlayTouch(_ sender:UIButton) {
      self.playerPlayOrPause()
    }

    func setTopAndBottomView(hidden:Bool) {
      if let controller = self.controller {
          controller.topViews.forEach { $0.isHidden = hidden }//!$0.isHidden
          controller.bottomViews.forEach { $0.isHidden = hidden }
      }
    }

    func playerPlayOrPause() {
      if self.avPlayer.status == .readyToPlay {
          self.imageView.isHidden = true
          self.avPlayerView.isHidden = false
          if self.avPlayer.rate != 1.0 {
              self.btnPlay.isHidden = true
              self.avPlayer.play()
              self.setTopAndBottomView(hidden: true)
          } else{
              self.btnPlay.isHidden = false
              self.avPlayer.pause()
              self.setTopAndBottomView(hidden: false)
          }
      }
    }
    func startOnPlay(){
      if self.avPlayer.status == .readyToPlay {
          self.imageView.isHidden = true
          self.avPlayerView.isHidden = false
          if self.avPlayer.rate != 1.0 {
              self.btnPlay.isHidden = true
              self.avPlayer.play()
              self.setTopAndBottomView(hidden: true)
          }else{
              self.avPlayer.seek(to: CMTime(value: 0 , timescale: 30))
              self.btnPlay.isHidden = true
              self.avPlayer.play()
              self.setTopAndBottomView(hidden: true)
          }
      }
    }
    func stopOnPlay(){
      if self.avPlayer.status == .readyToPlay {
          self.imageView.isHidden = true
          self.avPlayerView.isHidden = false
          
          self.btnPlay.isHidden = false
          self.avPlayer.pause()
          self.setTopAndBottomView(hidden: false)
      }
    }

}
